<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="操作时间" prop="operateTime">
          <el-date-picker
              v-model="queryParams.operateTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="!w-[240px]"
          />
        </el-form-item>
        <el-form-item label="旅行社名称" prop="deptId">
          <el-tree-select
              v-model="queryParams.deptId"
              placeholder="全部"
              :data="deptOptions"
              filterable
              clearable
              check-strictly
              :render-after-expand="false"
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryId">
          <el-tree-select
              v-model="queryParams.categoryId"
              placeholder="全部"
              :data="categoryOptions"
              filterable
              clearable
              check-strictly
              :render-after-expand="false"
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="操作人" prop="userName">
          <el-input
              v-model="queryParams.userName"
              placeholder="操作人"
              clearable
              @keyup.enter="handleQuery()"
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="操作类型" prop="operateType">
          <dict v-model="queryParams.operateType" code="operate_type" style="width: 200px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search/>
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh/>
            </template>
            重置
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-switch v-model="showStats"></el-switch>
          <span style="margin-left: 10px;">显示统计</span>
        </el-form-item>
      </el-form>
    </div>
    <div class="search-bar" v-if="showStats">
      <div class="stats-container">
        <div v-show="noData">
          <span class="text-gray">暂无数据</span>
        </div>
        <div v-show="!noData" class="stat-item" v-for="stat in statsData" :key="stat.categoryName">
          <span class="label">{{ stat.categoryName }}</span>
          <span class="value">出票{{ stat.outNum }}</span>
          <span class="value">预售{{ stat.sellNum }}</span>
        </div>
      </div>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
            v-hasPerm="['system:spotCount:delete']"
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
        >
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
        <el-button v-hasPerm="['system:spotCount:word']" type="primary" @click="handleExport()">
          <template #icon>
            <Download/>
          </template>
          导出
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column type="index" label="序号" width="80" align="center"/>
        <el-table-column
            key="deptName"
            label="旅行社名称"
            prop="deptName"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="categoryName"
            label="分类名称"
            prop="categoryName"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="userName"
            label="操作人"
            prop="userName"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="operateTime"
            label="操作时间"
            prop="operateTime"
            min-width="150"
            align="center"
        />
        <el-table-column
            key="num"
            label="操作数量"
            prop="num"
            min-width="150"
            align="center"
        />
        <el-table-column label="操作类型" width="150" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.operateType" code="operate_type"/>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template #default="scope">
            <el-button
                v-hasPerm="['system:spotCount:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit/>
              </template>
              详情
            </el-button>
            <el-button
                v-hasPerm="['system:spotCount:delete']"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete/>
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- 统计表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="旅行社名称：" prop="deptName">
          {{formData.deptName}}
        </el-form-item>

        <el-form-item label="分类名称：" prop="categoryName">
          {{formData.categoryName}}
        </el-form-item>
        <el-form-item label="操作人：" prop="userName">
          {{formData.userName}}
        </el-form-item>
        <el-form-item label="操作时间：" prop="operateTime">
          {{formData.operateTime}}
        </el-form-item>

        <el-form-item label="操作数量：" prop="num">
          {{formData.num}}
        </el-form-item>

        <el-form-item label="操作类型：" prop="operateType">
          <span v-if="formData.operateType == 1">出票</span>
          <span v-else-if="formData.operateType == 2">预售</span>
          <span v-else></span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

defineOptions({
  name: "SpotCount",
  inheritAttrs: false,
});

import SpotCountAPI, {SpotCountPageVO, SpotCountForm, SpotCountPageQuery, SpotCountDTO} from "@/api/system/spot-count";
import DeptAPI from "@/api/system/dept";
import SpotCategoryAPI from "@/api/system/spot-category";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const deptOptions = ref<OptionType[]>();
const categoryOptions = ref<OptionType[]>();
const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);
const showStats = ref(true); // 默认显示统计信息
const noData = ref(false); // 默认显示统计信息
// 统计数据
const statsData = ref<SpotCountDTO[]>([]);

const now = new Date();
const startOfDay = new Date(now);
startOfDay.setHours(0, 0, 0, 0);

const endOfDay = new Date(now);
endOfDay.setHours(23, 59, 59, 999);

const format = (date: Date) => {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  const h = String(date.getHours()).padStart(2, '0');
  const mi = String(date.getMinutes()).padStart(2, '0');
  const s = String(date.getSeconds()).padStart(2, '0');
  return `${y}-${m}-${d} ${h}:${mi}:${s}`;
};

const queryParams = reactive<SpotCountPageQuery>({
  pageNum: 1,
  pageSize: 10,
  operateTime: [format(startOfDay), format(endOfDay)]
});

// 统计表格数据
const pageData = ref<SpotCountPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 统计表单数据
const formData = reactive<SpotCountForm>({});

// 统计表单校验规则
const rules = reactive({});

/** 查询统计 */
function handleQuery() {
  loading.value = true;
  noData.value = false;
  SpotCountAPI.getCount(queryParams)
      .then((data) => {
        if (data.length === 0) {
          noData.value = true;
        } else {
          const processedData = data.map(item => ({
            categoryName: item.categoryName || '未知分类',
            outNum: item.outNum || 0,
            sellNum: item.sellNum || 0
          }));
          statsData.value = processedData;
        }
      })
      .catch(() => {
        // 异常情况下也显示“暂无数据”
        statsData.value = [{categoryName: '暂无数据', outNum: 0, sellNum: 0}];
      });

  SpotCountAPI.getPage(queryParams)
      .then((data) => {
        pageData.value = data.list;
        total.value = data.total;
      })
      .finally(() => {
        loading.value = false;
      });
}

/** 重置统计查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开统计弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "统计详情";
    SpotCountAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  }
}

/** 提交统计表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        SpotCountAPI.update(id, formData)
            .then(() => {
              ElMessage.success("修改成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      } else {
        SpotCountAPI.add(formData)
            .then(() => {
              ElMessage.success("新增成功");
              handleCloseDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭统计弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除统计 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
      () => {
        loading.value = true;
        SpotCountAPI.deleteByIds(ids)
            .then(() => {
              ElMessage.success("删除成功");
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
      },
      () => {
        ElMessage.info("已取消删除");
      }
  );
}

function handleExport() {
  SpotCountAPI.export(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(response.headers["content-disposition"].split(";")[1].split("=")[1]);
    const fileType =
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], {type: fileType});
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

if (onMounted) {
  onMounted(async () => {
    // 加载区域下拉数据源
    deptOptions.value = await DeptAPI.getOptions();
    // 加载分类下拉数据源
    categoryOptions.value = await SpotCategoryAPI.getOptions();
    handleQuery();
  });
}
</script>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left !important;
}

:deep(.el-popper) {
  max-width: 300px;
}
</style>

<style scoped>
.stats-container {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.label {
  margin-right: 10px;
  font-size: 16px;
  color: #6331d3;
  font-weight: bold;
}

.value {
  margin-right: 10px;
  font-size: 16px;
  color: #6331d3;
  font-weight: bold;
}
</style>
<style>
.text-gray {
  color: #999;
}
</style>
